/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.service.reliable.impl;


import java.util.Hashtable;

import cgl.narada.event.EventHeaders;
import cgl.narada.event.EventID;
import cgl.narada.event.NBEvent;
import cgl.narada.event.NBEventTypes;
import cgl.narada.event.TemplateProfileAndSynopsisTypes;
import cgl.narada.matching.Profile;
import cgl.narada.service.ServiceException;
import cgl.narada.service.client.ClientService;
import cgl.narada.service.client.EventConsumer;
import cgl.narada.service.client.EventProducer;
import cgl.narada.service.client.NBEventListener;
import cgl.narada.service.client.NBRecoveryNotification;
import cgl.narada.service.client.SessionService;
import cgl.narada.service.client.impl.EventProducerImpl;
import cgl.narada.service.qos.ProducerConstraints;
import cgl.narada.service.qos.QosEvent;
import cgl.narada.service.qos.impl.CommunicationsService;
import cgl.narada.service.qos.impl.ProducerConstraintsImpl;
import cgl.narada.service.qos.impl.QosEventImpl;
import cgl.narada.service.qos.impl.QosServiceImpl;
import cgl.narada.service.reliable.events.RdNegotiationsServiceEvent;
import cgl.narada.service.reliable.events.RdRecoveryEntityRequest;
import cgl.narada.service.reliable.events.RdRecoveryResponse;


/** This class is responsible for ensuring that entity events are published
    reliably 
    
    @author Shrideep Pallickara
    $Date$
    $Revision$
*/

public class RdPublishingEntityImpl implements NBEventListener, RdDebugFlags {
  private CommunicationsService communicationsService;
  private Hashtable publisherPercolators;

  private Hashtable qosEventsTable;

  private RdCommunicationsMultiplexerImpl rdsMultiplexer;
  private String moduleName = "RdPublishingEntityImpl: ";
  private QosServiceImpl qosServiceImpl;
  private RdFragmentationHelper fragmentationHelper;

  public RdPublishingEntityImpl(QosServiceImpl qosServiceImpl,
				CommunicationsService communicationsService) 
    throws ServiceException {
    this.qosServiceImpl = qosServiceImpl;
    this.communicationsService = communicationsService;
    fragmentationHelper = new RdFragmentationHelper(qosServiceImpl);
    
    publisherPercolators = new Hashtable();
    qosEventsTable = new Hashtable();
    rdsMultiplexer = new RdCommunicationsMultiplexerImpl();
    rdsMultiplexer.registerPublishingEntity(this);
  }


  public void terminateService() throws ServiceException {
    rdsMultiplexer.terminateService();
  }
  
  public void publishReliably(QosEvent qosEvent) throws ServiceException {
    NBEvent nbEvent = qosEvent.getNBEvent();
    
    if (!nbEvent.hasEventHeaders() ) {
      throw new ServiceException(moduleName + "Trying to reliably publish" +
				 " an event that has no headers. Error!");
    }
    
    EventHeaders eventHeaders = nbEvent.getEventHeaders();
    int entityId = eventHeaders.getSource();
    
    if (entityId == 0) {
      throw new ServiceException(moduleName + 
				 "Invalid entity identifier = 0 specified "); 
    }
    
    
    EventID eventId = qosEvent.getEventId();
    if (eventId == null) {
      throw new ServiceException(moduleName + "Specified eventId == null");
    }
    

    if (qosEventsTable.containsKey(eventId)) {
      throw new ServiceException(moduleName + 
				 "Event currently queued for publishing");
    }
    
    int templateId = eventHeaders.getTemplateId();
    ProducerConstraints constraints = qosEvent.getProducerConstraints();

    
    if (constraints.getTemplateInfo().getTemplateId() != templateId) {
      throw new ServiceException(moduleName + "The template id contained in" +
				 " the event and constraints do not match!");
      
    }
    
    
    Object entityKey = new Integer(entityId);
    if (!publisherPercolators.containsKey(entityKey)) {
      PublisherPercolator percolator = createPublisherPercolator(entityId);
      publisherPercolators.put(entityKey, percolator);
    }
    
    PublisherPercolator percolator = 
      (PublisherPercolator) publisherPercolators.get(entityKey);
    qosEventsTable.put(eventId, qosEvent);
    
    percolator.publishEvent(nbEvent);
  }
  
  
  private PublisherPercolator createPublisherPercolator(int entityId) 
    throws ServiceException {
    
    /** Subscribe to the right topics and such */
    ClientService clientService = SessionService.getClientService(entityId);
    
    if (!clientService.isInitialized()) {
      throw new ServiceException(moduleName + "Client service for entity=" + 
				 entityId +
				 " should have been previously initialized");
    }
    
    String subscription = entityId + "/Negotiations";
    Profile profile = 
      clientService.createProfile(TemplateProfileAndSynopsisTypes.STRING, 
				  subscription);

    String subscription2 = entityId + "/Recovery/Publisher";
    Profile profile2 = 
      clientService.createProfile(TemplateProfileAndSynopsisTypes.STRING, 
				  subscription2);

    EventConsumer consumer = clientService.createEventConsumer(this);
    consumer.subscribeTo(profile);
    consumer.subscribeTo(profile2);

    EventProducer producer = clientService.createEventProducer();
    PublisherPercolator percolator = 
      new PublisherPercolator(entityId, producer);
    percolator.setFragmentationHelper(fragmentationHelper);
    return percolator;
  }


  protected void publishEvent(NBEvent nbEvent) {

  }

  /** After the event receives a negotiation acknowledgement the indication is
      that the event has been successfully stored onto stable storage */
  public void eventHasBeenReliablyPublished(NBEvent nbEvent) {
    EventID eventId = nbEvent.getEventHeaders().getEventId();
    if (qosEventsTable.containsKey(eventId)) {
      QosEvent qosEvent = (QosEventImpl) qosEventsTable.remove(eventId);
      ProducerConstraintsImpl producerConstraints = 
	(ProducerConstraintsImpl) qosEvent.getProducerConstraints();
      int producerId = producerConstraints.getProducerId();
      if (RdPublishingEntityImpl_Debug) {
	System.out.println(moduleName + "Event " + eventId + 
			   " reliably published for producer = " + producerId +
			   " entityId = " + producerConstraints.getEntityId());
      }
    }
  }
  
  
  /** Removes an event from the queue based on the fact that event was 
      previously published. This method would be invoked from the publisher
      percolator */
  public void removeEventFromQueue(NBEvent nbEvent) {
    EventID eventId = nbEvent.getEventHeaders().getEventId();
    if (qosEventsTable.containsKey(eventId)) {
      qosEventsTable.remove(eventId);
    }
    
  }
  
  public void 
  processNegotiationServiceEvent(RdNegotiationsServiceEvent negotiationEvent) {
    Object entityKey = new Integer(negotiationEvent.getEntityId());

    if (publisherPercolators.containsKey(entityKey)) {
      PublisherPercolator percolator = 
	(PublisherPercolator)publisherPercolators.get(entityKey);
      percolator.processNegotiationsEvent(negotiationEvent);
      return;
    }
    
    
    System.out.println(moduleName + "Received negotiation event without" +
		       " valid percolator in place!"); 
    
  }
  

  public void processRecoveryResponse(RdRecoveryResponse recoveryResponse) {
    Object entityKey = new Integer(recoveryResponse.getEntityId());
    int entityId = recoveryResponse.getEntityId();
    int templateId = recoveryResponse.getTemplateId();
    long recoveryId = recoveryResponse.getRecoveryRequestId();

    if (publisherPercolators.containsKey(entityKey)) {
      PublisherPercolator percolator = 
	(PublisherPercolator)publisherPercolators.get(entityKey);
      percolator.processRecoveryResponse(recoveryResponse);
      
    } else {
      System.out.println(moduleName + "Received recovery response without" +
			 "a valid percolator in place!"); 
      return;
    }

    EventProducerImpl recoveringProducer = 
      qosServiceImpl.getRecoveringProducer(recoveryId);

    if (recoveringProducer == null) {
      System.out.println(moduleName + "No registered producer available for" +
			 recoveryResponse);
      return;
    }
    
    NBRecoveryNotification recoveryNotification;
    String recoveringInfo = "Recovery process updated the publishers " +
      "catenation number to [" + 
      recoveryResponse.getPublisherRecoveryInfo().getCatenationNumber() 
      + "]\n\n";
    

    recoveryNotification = 
	 new NBRecoveryNotification(recoveryId, entityId, templateId,
				    true, recoveringInfo);
    recoveringProducer.propagateRecoveryNotification(recoveryNotification);
    return;
  }
  
  
  public void issueRecoveryRequest(RdRecoveryEntityRequest recoveryRequest)
    throws ServiceException {
    int entityId = recoveryRequest.getEntityId();
    Object entityKey = new Integer(entityId);

    if (!publisherPercolators.containsKey(entityKey)) {
      PublisherPercolator percolator = createPublisherPercolator(entityId);
      publisherPercolators.put(entityKey, percolator);
    }

    PublisherPercolator percolator = 
      (PublisherPercolator)publisherPercolators.get(entityKey);
    percolator.issueRecoveryRequest(recoveryRequest);
  }

  

  public void onEvent(NBEvent nbEvent) {
    int eventType = nbEvent.getEventType();
    
    if (eventType == NBEventTypes.NORMAL_EVENT) {
      System.out.println(moduleName + "Received normal event .." + nbEvent);
      
    }
    
    if (eventType == NBEventTypes.RELIABLE_DELIVERY_EXCHANGE ) {
      if (RdPublishingEntityImpl_Debug) {
	System.out.println(moduleName + 
			   "Received reliable delivery Xchange.." );
      }
      rdsMultiplexer.manageReliableDeliveryExchange(nbEvent);
      return;
    }
    
    System.out.println(moduleName + "Unknown event type [" + eventType + 
		       "] received ");
  }
}
